package com.kamisama.utopia.controller;

import com.kamisama.utopia.assembler.WeChatAssembler;
import com.kamisama.utopia.dto.OpenIdDto;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {

    @Autowired
    private WeChatAssembler weChatAssembler;

    @PostMapping(value = "user/login")
    public ResponseEntity<String> userLogin(@RequestParam("jscode") String jscode, HttpServletRequest request) {
        HttpSession session = request.getSession();
        OpenIdDto openIdDto = weChatAssembler.getOpenId(jscode);
        session.setAttribute(openIdDto.getOpenid(), openIdDto.getSession_key());
        return ResponseEntity.ok(openIdDto.getOpenid());
    }

    @GetMapping(value = "user/checksession")
    public ResponseEntity<Boolean> userCheckSession(@RequestParam("openId") String openId, HttpServletRequest request){
        HttpSession session = request.getSession();
        Object sessionKey = session.getAttribute(openId);
        if (ObjectUtils.isEmpty(sessionKey)){
            return ResponseEntity.ok(false);
        } else {
            return ResponseEntity.ok(true);
        }
    }



}
